<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader :buttons="[]">
            <template #refreshAppend>
                <div>
                    <div class="mb-3">
                        <el-form-item label="平台">
                            <el-button :type="currentPlatformIndex === index ? 'primary' : 'info'" plain v-for="(item,index) in platformList"
                         :key="item.id" @click="selectPlatform(item.id,index)">{{item.name}}</el-button>
                        </el-form-item>
                    </div>
                    <div>
                        <el-button class="table-header-operate" type="primary" @click="(infoShow = true), (currentRow = {})"
                            ><Icon name="fa fa-plus" class="mr-2" />创建采购</el-button
                        >
                        <el-select v-model="filterParams.admin_id" class="ml-3 w-40" clearable placeholder="采购员" v-if="purchaserIndex == -1"
                            ><el-option v-for="item in purchaserList" :value="item.id" :key="item.id" :label="item.nickname"></el-option
                        ></el-select>
                        <el-input v-model="filterParams.purchase_no" class="ml-3 w-40" placeholder="采购订单" clearable></el-input>
                        <el-input v-model="filterParams.express" class="ml-3 w-40" placeholder="物流单号" clearable></el-input>
                        <el-date-picker v-model="filterParams.start_time" type="date" placeholder="请选择日期"
                            value-format="YYYY-MM-DD" class="ml-2 w-52" />
                        <span class="ml-2">~</span>
                        <el-date-picker v-model="filterParams.end_time" type="date" placeholder="请选择日期"
                            value-format="YYYY-MM-DD" class="ml-2 w-52" />
                        <el-button class="ml-3" @click="handleSearch('reset')"
                            ><Icon name="fa fa-refresh" class="text-current text-sm mr-1"></Icon>重置</el-button
                        >
                        <el-button type="primary" @click="handleSearch('search')"
                            ><Icon name="fa fa-search" class="text-white text-sm mr-1"></Icon>查询</el-button
                        >
                    </div>
                </div>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <div class="bg-white mt-2 p-3">
            <Table ref="tableRef">
                <template #detail>
                    <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                    <el-table-column prop="username" label="采购详情" :align="'center'">
                        <template #default="scope">
                            <el-button type="primary" @click="getDetail(scope.row)">点击查看详情</el-button>
                        </template>
                    </el-table-column>
                </template>
                <template #status>
                    <el-table-column label="物流状态" :align="'center'" width="100">
                        <template #default="scope">
                            <div class="group transition ease-in-out">
                                <el-popover
                                    placement="right"
                                    :width="200"
                                    trigger="click"
                                    :hide-after="0"
                                >
                                    <template #reference>
                                        <el-button size="small">
                                            {{ scope.row.status == 1 ? '已入库' : scope.row.status == 2 ? '未入库' : scope.row.status == 3 ? '物流中' : '未知' }}
                                        </el-button>
                                    </template>
                                    <span class="text-sm">物流单号:{{ scope.row.express || '暂无单号' }}</span>
                                </el-popover>
                            </div></template
                        >
                    </el-table-column>
                </template>
                <template #operate>
                        <el-table-column label="操作" :align="'center'">
                            <template #default="scope">
                                <div class="flex justify-center">
                                    <el-tooltip class="box-item" effect="dark" content="入库" placement="top" v-if="scope.row.status === 3">
                                        <el-button type="primary" size="small" @click="toWarehousing(scope.row)" class="w-7 h-7">
                                            <Icon name="fa fa-plus" class="text-white text-lg"></Icon>
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="编辑" placement="top" v-if="scope.row.status === 3">
                                        <el-button type="primary" size="small" @click="(infoShow = true), (currentRow = scope.row),(status = 1)" class="ml-3 w-7 h-7">
                                            <Icon name="fa fa-pencil" class="text-white text-lg"></Icon>
                                        </el-button>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="异常处理" placement="top" v-if="scope.row.status === 1 && scope.row.abnormal > 0">
                                        <el-button type="danger" size="small" @click="exceptionHandling(scope.row)" class="ml-3 w-7 h-7">
                                            <Icon name="fa fa-exclamation-circle" class="text-white text-lg"></Icon>
                                        </el-button>
                                    </el-tooltip>
                                    <el-popconfirm
                                        width="220"
                                        confirm-button-text="删除"
                                        cancel-button-text="取消"
                                        title="确定删除选中记录?"
                                        @confirm="handleDelete(scope.row)"
                                        confirm-button-type="danger"
                                        v-if="scope.row.status === 3"
                                    >
                                        <template #reference>
                                            <div>
                                                <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                                                    <el-button type="danger" size="small" class="ml-3 w-7 h-7">
                                                        <Icon name="fa fa-trash" class="text-white text-lg"></Icon>
                                                    </el-button>
                                                </el-tooltip>
                                            </div>
                                        </template>
                                    </el-popconfirm>
                                </div>
                            </template>
                        </el-table-column>
                    </template>
            </Table>
        </div>

        <!-- 表单 -->
        <!-- <PopupForm /> -->
        <PurchaseInfo
            :modelValue="infoShow"
            @close="(value: any) => (infoShow = value)"
            :purchaserList="purchaserList"
            @update="handleClick()"
            :data="currentRow"
            :platform="filterParams.platform"
            :status="status"
            :purchaserIndex="purchaserIndex"
        ></PurchaseInfo>

        <!-- 采购明细弹窗 -->
        <el-dialog v-model="isShowDetail" destroy-on-close title="采购明细" width="80%" >
            <Product :detail_id="detail_id" :key="detail_id" :isEdit="false"></Product>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import createAxios from '/@/utils/axios'
// import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { ElMessage } from 'element-plus'
import PurchaseInfo from './PurchaseInfo.vue'
import Product from '/@/components/product/product.vue'
defineOptions({
    name: 'xmwms/purchase/order',
})

const { t } = useI18n()
const tableRef = ref()
// const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
let filterParams = ref({
    platform: 1, //平台id
    purchase_no: '', // 采购单号
    express: '', //物流单号
    admin_id: '', // 采购员
    start_time: '', // 开始时间
    end_time: '', // 结束时间
}) // 搜索参数
let currentRow = ref({}) // 当前行数据
let platformList: any = ref([]) // 平台列表
let currentPlatformIndex: any = ref(0) //当前选择平台索引
let purchaserList: any = ref([]) // 采购员列表
let infoShow = ref(false) // 弹窗显示隐藏
let isShowDetail = ref(false) //采购明细弹窗
let detail_id = ref(1) //采购明细id
let status = ref(1) //1添加与编辑 2入库 3异常处理
let purchaserIndex = ref(-1) //当前操作人是否是采购员（-1不是,其他是）

// 给第一个按钮加上点击事件
// optButtons[0].click = (row: TableRow, field: TableColumn) => {
//     infoShow.value = true
//     currentRow.value = row
// }

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/xmwms.purchase.Order/'),
    {
        pk: 'id',
        column: [
            { label: '编号', prop: 'id', align: 'center', operator: 'RANGE', sortable: false , width: 100, },
            { label: '采购订单号', prop: 'purchase_no', align: 'center', operator: 'RANGE', sortable: false },
            {
                label: '金额',
                prop: 'money',
                align: 'center',
                width: 100,
            },
            {
                label: '数量',
                prop: 'sum',
                align: 'center',
                width: 100,
            },
            {
                label: '物流状态',
                prop: 'status',
                align: 'center',
                render: 'slot',
                slotName: 'status',
                width: 100,
            },
            {
                label: '采购员',
                prop: 'admin_text',
                align: 'center',
            },
            {
                label: '采购日期',
                prop: 'purchase_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd',
            },
            {
                label: '采购详情',
                prop: 'detail',
                render: 'slot',
                slotName: 'detail',
                align: 'center',
            },
            { label: '付款附件', prop: 'image', align: 'center', render: 'image', operator: false },
            {
                label: '创建日期',
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            { label: t('Operate'), align: 'center', width: 100, render: 'slot', slotName: 'operate' },
            // { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {},
    }
)
let filter = ref(baTable.table.filter)
provide('baTable', baTable)

const handleClick =() => {
    baTable.getIndex()?.then(() => {})
}

// 获取平台列表
const getPlatformList = () => {
    createAxios({ url: '/admin/xmwms.Platform/index', method: 'get'}).then((res) => {
        if (res.code === 1) {
            platformList.value = res.data.list
            filterParams.value.platform = res.data.list[0].id
        }
    })
}

// 获取采购员列表
const getPurchaserList = () => {
    createAxios({ url: '/admin/auth.admin/select', method: 'get'}).then((res) => {
        if (res.code === 1) {
            purchaserList.value = res.data.list
            let adminInfo: any = localStorage.getItem('adminInfo');
            adminInfo = JSON.parse(adminInfo)
            //创建时赋值
            purchaserIndex.value = purchaserList.value?.findIndex((item:any) => adminInfo?.id == item.id)
        }
    })
}

//选择平台
const selectPlatform = (id: any,index: any) => {
    currentPlatformIndex.value = index
    filterParams.value.platform = id
    handleSearch('search')
}

// 删除商品
const handleDelete = (row: any) => {
    baTable.table.loading = true
    createAxios({ url: '/admin/xmwms.purchase.Order/delete', method: 'DELETE', params: { id: row.id } }).then((res) => {
        if (res.code === 1) {
            ElMessage({ type: 'success', message: res.msg })
            handleClick()
        }
    })
}

//搜索操作
const handleSearch = (type: string) => {
    if (type === 'reset') {
        filterParams.value = {
            platform: 1, //平台id
            purchase_no: '', // 采购单号
            express: '', //物流单号
            admin_id: '', // 采购员
            start_time: '', // 开始时间
            end_time: '', // 结束时间
        }
    }
    //赋值给baTable的filter对象
    filter.value!.platform = filterParams.value.platform
    filter.value!.purchase_no = filterParams.value.purchase_no
    filter.value!.express = filterParams.value.express
    filter.value!.admin_id = filterParams.value.admin_id
    filter.value!.start_time = filterParams.value.start_time
    filter.value!.end_time = filterParams.value.end_time
    baTable.getIndex()?.then(() => {})
}

//查看详情
const getDetail = (row: any) => {
    detail_id.value = row.id
    isShowDetail.value = true
 }

 //入库
const toWarehousing = (row: any) => {
    currentRow.value = row
    infoShow.value = true
    status.value = 2
 }

 //异常处理
 const exceptionHandling = (row: any) => {
    currentRow.value = row
    infoShow.value = true
    status.value = 3
 }
 

onMounted(() => {
    getPlatformList()
    getPurchaserList()
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss"></style>
